/**
 * Created by Administrator on 2016/3/16.
 */
var GCSDK=(function(){

   var gamec=window.webkit?top:window;

   var version="1.0.0";
   function GCSDK()
   {
     
   }
   GCSDK.init=function()
   {
		gamec.login=function(data)
		{
		   //alert(">>>loginCallback:"+JSON.stringify(data));
		   data.sessionKey=data.refreshToken=data.qbopenkey;
		   data.headimg=data.avtorUrl=data.avatarUrl;
		   data.desc=data.msg;
		   data.unionUserId=data.qbopenid;
		   GCSDK.loginCb&&GCSDK.loginCb(data);
		   GCSDK.loginCb=null;
		   return data;
		};
		
		gamec.refreshToken2=function(data)
		{
		   GCSDK.rftcb&&GCSDK.rftcb(data);
		   GCSDK.rftcb=null;
		   return data;
		};
		
		gamec.getFriends=function(data)
		{
		   data.desc=data.msg;
		   data.friends=[];
		   for(var d in data.items)
		   { 
		       if(data.items[d].openid!="")
				data.friends.push(data.items[d].openid);
		   }
		
		   GCSDK.gfcb&&GCSDK.gfcb(data);
		   GCSDK.gfcb=null;
		    return data;
		}
		
		gamec.share=function(data)
		{
		   data.result=data.errorid;
		   data.desc=data.errorMessage;
		   GCSDK.shcb&&GCSDK.shcb(data);
		   GCSDK.shcb=null;
		    return data;
		}
		
		gamec.queryVirtualCurrency=function(data)
		{
		   data.desc=data.msg;
		   GCSDK.qvcb&&GCSDK.qvcb(data);
		   GCSDK.qvcb=null;
		    return data;
		}
		
		gamec.pay=function(data)
		{
		   //alert(">>>payCallBack:"+JSON.stringify(data));
		   var p_nResult=data.resultCode;
			switch(p_nResult)
			{
			case -1:
			   p_nResult=-2;
			   break;
			case 2:
				p_nResult=-1;
				 break;
			case 3:
				p_nResult=-6;
				break;
			}
		   data.result=p_nResult;
		   data.desc=data.resultMsg;
		   GCSDK.paycb&&GCSDK.paycb(data);
		   GCSDK.paycb=null;
		    return data;
		}
		
		gamec.getUserInfo=function(data)
		{
		   data.desc=data.resultstr;
		   GCSDK.getUIcb&& GCSDK.getUIcb(data);
		   return data;
		}
		
   }
   GCSDK.login=function(data,callback)
   {
	 data.msgType=100;
	 data.msgVersion=version;
	 console.log(">>>>>>>>>>>>>login"+JSON.stringify(data));
	 //alert(">>>login:"+JSON.stringify(data));
   	 GCSDK.loginCb=callback;
     qqgameLoginSubmit(data);
   }
   
   GCSDK.getAvailableLoginType=function(data,callback)
   {
	 data.msgType=109;
	 data.msgVersion=version;
	 callback&&callback({result:-2,desc:"not support"});
   }
   
   GCSDK.refreshToken=function(data,callback)
   {
      data.msgType=106;
	  data.msgVersion=version;
	  //GCSDK.rftcb=callback;
	  //qqgameRefreshToken2Submit(data);
	  callback&&callback({result:-2,desc:"not support"});
   }
   
   GCSDK.logout=function(data,callback)
   {
      callback&&callback({result:0,desc:"logout success"});
   }
   
   GCSDK.getGameFriends=function(data,callback)
   {
      data.msgType=105;
	  data.msgVersion=version;
	  console.log(">>>>>>>>>>>>>getGameFriends"+JSON.stringify(data));
	  GCSDK.gfcb=callback;
	  qqgameGetfriendsSubmit(data);
   }
   
   GCSDK.share=function(data,callback)
   {
	  data.msgType=104;
	  data.msgVersion=version;
	  console.log(">>>>>>>>>>>>>share"+JSON.stringify(data));
	  GCSDK.shcb=callback;
	  qqgameShareSubmit(data);
   }
   
   GCSDK.queryVirtualCurrency=function(data,callback)
   {
      data.msgType=107;
	  data.msgVersion=version;
      GCSDK.qvcb=callback;
	  qqgameQueryVirtualCurrencySubmit(data);
   }
   
   GCSDK._pay=function(data,callback)
   {
        data.msgType=101;
		data.msgVersion=version;
        GCSDK.paycb=callback;
		//alert(">>>pay:"+JSON.stringify(data));
		qqgamePaySubmit(data);
   }
   
   GCSDK.payBack=function(data,res,callback)
   {
	  	 var sdk=window.LayaBoxMarket.getInstance().spSdk;
             var url=data.other.notifyUrl;
             url+="?ts="+Date.now()+
                  "&pf="+sdk.loginType+
                  "&charset=utf-8"+
                  "&gameappid="+data.appid+
                  "&gameopenid="+encodeURIComponent(data.qbopenid)+
                  "&gameopenkey="+encodeURIComponent(data.qbopenkey)+
                  "&paytoken="+sdk.payToken+
                  "&orderno="+res.orderno+
                  "&payamt="+res.realSaveNum+
                  "&layaorderno="+data.customMeta;
				  
				LayaCommon.getJson(url,function(data)
				{ 
				   if(data&&data.ret==0)
					      callback&&callback({"result":0,"desc":"pay success"});
                   else
                		callback&&callback({"result":-2,"desc":"pay error"});
				},
                function(err)
				{
				   callback&&callback({"type":"payresult","result":-4,"desc":"net error"});
				}); 
   }
   
   GCSDK.pay=function(data,callback)
   {
      GCSDK.queryVirtualCurrency({appsig:data.appsig,appsigData:data.appsigData,qbopenid:data.qbopenid,appid:data.appid},
	  function(result)
	  {
	    if(result.result==0)
		{
		    if(result.balance<data.payValue)
			{
				data.payType=0;
				GCSDK._pay(data,function(res)
				{
				   if(res.result!=0)
				   {
					 callback(res);
				   }
				   else
				   {
					 GCSDK.payBack(data,res,callback);
				   }
				});
			}
			else
			{
				data.payType=1;
			    GCSDK._pay(data,function(res)
				{
				  if(res.result==0)
					  GCSDK.payBack(data,res,callback);
					 else
					  callback(res);
				});
			}
		}
		else
		{
		  callback&&callback(result);
		}
	  });
   }
   
   GCSDK.getUserInfo=function(data,callback)
   {
        data.msgType=108;
		data.msgVersion=version;
        GCSDK.getUIcb=callback;
		//alert(">>>pay:"+JSON.stringify(data));
		qqgameGetUserInfoSubmit(data);
   }
   return GCSDK;
})()
 
var SPSdk = (function () {

    var SDK = "http://minigame.qq.com/js2.0/m_h5frame/h5frameIos.js";
	//var SDK="http://api.dongdong.feng.inner.layabox.com/MarketH5/sp/h5frameIos.js";
    var qqsdk;

    function SPSdk() {
        this.layaStorage = new LayaStorageH5("LAYA_H5_SP_LOCAL_INFO");
        this.spId;
        this.appId;
        this.appKey = "";
        this.token = "";
        this.spFname = "";
        this.qbopenid = "";
        this.qbopenkey = "";
        this.loginType = "";
        this.refreshkey = "";
		this.payToken="";
		this.appsig="";
		this.appsigData="";
    }

    var __proto = SPSdk.prototype;
    __proto.getAvailableLoginType = function (param, callback){
        console.log("QQGameCenter获得登录方式：" + JSON.stringify(param));
        var m_this = this;
        qqsdk && qqsdk.getAvailableLoginType({appid:m_this.appId},function(rsp)
        {
            if(rsp.result == 0)
            {
                callback&&callback(JSON.stringify(rsp));
            }else
            {
                callback&&callback(JSON.stringify({result:-1,desc:rsp.msg}));
            }
        });
    }
    __proto.login = function (param, callback, shareHandler) {
        console.log("QQGameCenter登录：" + JSON.stringify(param));
        var m_this = this;
        var data = param.data;
        m_this.loginType = param.authorizeType || m_this.layaStorage.getLocalStore("YXDT_LOGIN_TYPE");
		if(!m_this.loginType)
		{
		    callback&&callback({result:1000,data:{"loginType":2},desc:"no login"});
			return;
		}
        m_this.layaStorage.setLocalStore("YXDT_LOGIN_TYPE",m_this.loginType);
		this.appsig=data.signkey;
		this.appsigData=data.signdata;
        qqsdk && qqsdk.login({appid:m_this.appId,appsig:data.signkey,appsigData:data.signdata,loginType:m_this.loginType},function(data)
        {
           if(data.result == 0)
           {
		       data.type=m_this.loginType;
			   data.marketName="GameCenterH5";
               data.spuid = data.qbopenid;
               data.nickname = data.nickName;
               m_this.qbopenid = data.qbopenid;
               m_this.qbopenkey = data.qbopenkey;
               m_this.refreshkey = data.refreshToken;
			   m_this.payToken=data.payToken;
           }
		   else
		   {
		      data.data={"loginType":2};
		   }
           callback&&callback(data);
        });
    }
    __proto.logout = function (param, callback){
        console.log("QQGameCenter登出：" + JSON.stringify(param));
        var m_this = this;
        m_this.layaStorage.removeLocalStore("YXDT_LOGIN_TYPE");
        qqsdk && qqsdk.logout({appid:m_this.appId,qbopenid:m_this.qbopenid,loginType:""},function(data)
        {
            callback&&callback(JSON.stringify(data));
        });
    }

    __proto.refreshToken = function (param, callback){
        console.log("X5刷新token：" + JSON.stringify(param));
        var m_this = this;
		this.loginType=param.loginType;
		this.appsig=param.appsig;
		this.appsigData=param.appsigdata;
        qqsdk && qqsdk.login({appid:m_this.appId,appsig:param.appsig,appsigData:param.appsigdata,loginType:param.loginType},function(data)
        {
           if(data.result == 0)
           {
		       data.type=m_this.loginType;
			   data.marketName="GameCenterH5";
               data.spuid = data.qbopenid;
               data.nickname = data.nickName;
               m_this.qbopenid = data.qbopenid;
               m_this.qbopenkey = data.qbopenkey;
               m_this.refreshkey = data.refreshToken;
			   m_this.payToken=data.payToken;
           }
		   else
		   {
		      data.data={"loginType":2};
		   }
           callback&&callback(data);
        });
    }
    __proto.pay = function (param, callback) {
        console.log("X5充值：" + JSON.stringify(param));
        var m_this = this;
        if(param.ret == 0)
        {
			qqsdk && qqsdk.pay({other:param.data.other,appid:m_this.appId,appsig:this.appsig,appsigData:this.appsigData,qbopenid:this.qbopenid,qbopenkey:this.qbopenkey,payItem:param.data.goodsName,payInfo:param.data.goodsName,reqTime:Date.now(),payValue:param.data.amount/10,customMeta:param.data.orderId}, function (rsp) {
				callback&&callback(rsp);
			});
        }
		else
		{
		   callback&&callback({result:-6,desc:"pay error"});
		}
    }
    __proto.getGameFriends = function (param, callback){
        var m_this = this;
        qqsdk && qqsdk.getGameFriends({appid:m_this.appId,appsig:this.appsig,qbopenid:m_this.qbopenid,qbopenkey:m_this.qbopenkey},function(data)
        {
            data.friendslist = JSON.stringify(data.friends);
            callback&&callback(JSON.stringify(data));
        });
    }
    __proto.share = function (param, callback){
        var m_this = this;
        qqsdk && qqsdk.share({targetUrl:param.link,title:param.title,summary:param.content,imageLocalUrl:param.imgUrl,img_title:param.imgtitle,cus_txt:param.custxt,qbopenid:this.qbopenid},function(rsp)
        {
            callback&&callback(JSON.stringify(rsp));
        });
    }
    __proto.getUserInfo = function (param, callback){
        var m_this = this;
        qqsdk.getUserInfo && qqsdk.getUserInfo({appid:m_this.appId,qbopenid:m_this.qbopenid,qbopenkey:m_this.qbopenkey},function(rsp)
        {
             //data.result //result为0获取成功，否则失败
             //data.msg //传回的提示信息
             //data.nickName //用户昵称
             //data.avatarUrl //用户头像url
             //data.sex// 性别：0未知，1男，2女
             //data.city //城市
             //data.language //语言
             //data.isVip// 是否为vip
             //data.province// 省份
             //data.country// 国家
             //data.birthday //生日，不确定微信手q是否能取到
            callback&&callback(JSON.stringify(rsp));
        });
    }


    __proto.init = function (param, callback) {
        console.log("X5初始化：" + JSON.stringify(param));
        var m_this = this;
        LayaCommon.loadScript(SDK, function ()
        {
            qqsdk = window.qqsdk = GCSDK;
			qqsdk.init();
            m_this.access_token = param.access_token;
            m_this.spId = param.spId;
            m_this.appId = param.appId;
            m_this.spFname = param.spFname;
            //LayaBoxMarketH5.instance.getLocalInfo(["X5"],function(s)
            //{
            //    var data = null;
            //    if (s != null)
            //        data = JSON.parse(s);
            //    if(!data || !data.data || !data.data["X5"])
            //    return;
            //    m_this.qbopenid = data.data["X5"].x5_openid;
            //    m_this.qbopenkey = data.data["X5"].x5_tokenid;
            //    alert( m_this.qbopenid+","+m_this.qbopenkey);
            //})
            callback && callback({"result": 0, "desc": "OK", "sp_data": null});
        })
    }

    return SPSdk;
})();